package proxy;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * 代理服务请求类
 *
 * @author 王松
 * @mail 1720696548@qq.com
 * @date 2025/5/14 10:49
 */
@RestController
@RequestMapping("/proxy")
@Slf4j
public class ProxyController {

    @PostMapping
    public Result<Object> proxy(@RequestBody XjHttpRequest dto) {
        String logStr = "proxy to --> " + dto.getMethod() + ": " + dto.getUrl();
        try {
            HttpResponse httpResponse = HttpRequest.of(dto.getUrl())
                    .setMethod(dto.getMethod())
                    .setFollowRedirects(true)
                    .headerMap(dto.getHeaders() != null ? dto.getHeaders() : null, true)
                    .timeout(dto.getTimeout() != null ? dto.getTimeout() : 30 * 1000)
                    .form(dto.getForm() != null ? dto.getForm() : null)
                    .body(dto.getBody() != null ? dto.getBody() : null)
                    .execute();
            if (httpResponse.isOk()) {
                logStr += " /200";
                log.info(logStr);
                return Result.success(httpResponse.body());
            } else {
                logStr += " /" + httpResponse.getStatus();
                log.info(logStr);
                return Result.fail(httpResponse.getStatus(), httpResponse.body());
            }
        } catch (Exception e) {
            logStr += "/ " + 500 + " " + e.getMessage();
            log.info(logStr);
            return Result.fail(500, e.getMessage());
        }
    }
}
